/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.infrastructure.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * hallele_mc_core
 *
 * @author anle5
 * @since 2024/9/24 0:57
 */
@Slf4j
public class FileUtil {
    /**
     * md5
     *
     * @param file {@link  MultipartFile}
     * @return md5值
     */
    public static String md5(MultipartFile file) {
        try {
            byte[] uploadBytes = file.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(uploadBytes);
            return new BigInteger(1, digest).toString(16);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取文件后缀
     *
     * @param file {@link  MultipartFile}
     * @return 文件后缀
     */
    public static String getFileSuffix(MultipartFile file) {
        if (file == null) {
            return null;
        }

        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)) {
            return null;
        }

        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 获取文件后缀
     *
     * @param filename 文件名
     * @return 文件后缀
     */
    public static String getFileSuffix(String filename) {
        if (ObjectUtil.isBlank(filename) || !filename.contains(".")) {
            return null;
        }

        if (StringUtils.isBlank(filename)) {
            return null;
        }

        return filename.substring(filename.lastIndexOf(".") + 1);
    }
}
